package com.ziq.zcamp.dialog.share

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.text.TextUtils
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.Toast
import androidx.core.view.isVisible
import com.gmlive.camp.dialog.share.SharePicCacheInterface
import com.ziq.zcamp.R
import com.ziq.zcamp.bean.coupon.CouponInfo
import com.ziq.zcamp.constant.H5Url
import com.ziq.zcamp.constant.MerchantCouponType
import com.ziq.zcamp.databinding.LayoutSharePicCacheCouponBinding
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.UserManager
import com.ziq.zcamp.manager.WXAccount
import com.ziq.zcamp.merchant.coupon.CouponAdapterHelper
import com.ziq.zcamp.util.ImageUtil
import com.ziq.zcamp.util.StorageUtil
import com.ziq.zcamp.util.TimeUtil
import com.ziq.zcamp.util.ZXingCodeUtils
import com.ziq.zcamp.util.bitmap.BitmapUtil
import com.ziq.zcamp.util.io.IOUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.io.FileOutputStream
import java.net.URLEncoder

class SharePicCacheLayoutCoupon @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr), SharePicCacheInterface {

    var binding : LayoutSharePicCacheCouponBinding = LayoutSharePicCacheCouponBinding.inflate(LayoutInflater.from(context), this, true)

    var imageList = mutableListOf<String>()
    var way = ""

    var couponDetails : CouponInfo? = null

    private val uidSuffix by lazy{
        val id = UserManager.instance.userInfo.value?.id.toString()
        if (id.isEmpty()){
            ""
        }else{
            "&shareuid=${id}"
        }
    }

    @SuppressLint("SetTextI18n")
    fun setCouponData(data: CouponInfo){
        couponDetails = data
        way = "coupon"

        binding.tvDiscountRange.text = when(data.applicate){
            1->{"指定商品"}
            else->{"全场通用"}
        }
        when(data.coupon_type){
            MerchantCouponType.Discount.value ->{
                binding.tvDiscountSymbol.isVisible = false
                binding.tvDiscountDiscount.isVisible = true

                binding.tvDiscountNumerical.text =
                    CouponAdapterHelper.obtainMoneyRate(data.discounts_way?.rate_off_way?.rate)

                binding.tvDiscountName.text = "满￥${CouponAdapterHelper.obtainMoneyText(data.discounts_way?.rate_off_way?.full_money)}可用"
            }
            MerchantCouponType.Reduction.value ->{
                binding.tvDiscountSymbol.isVisible = true
                binding.tvDiscountDiscount.isVisible = false

                binding.tvDiscountNumerical.text =
                    CouponAdapterHelper.obtainMoneyText(data.discounts_way?.money_off_way?.discount_money)

                binding.tvDiscountName.text = "满￥${CouponAdapterHelper.obtainMoneyText(data.discounts_way?.money_off_way?.full_money)}可用"
            }
        }
        binding.tvDiscountSurplus.text = "每人限领1张"
        val timeStringBuilder = StringBuilder()
        timeStringBuilder.append("有效期始：${TimeUtil.yyyy_MM_dd_time_SPOT_FORMATTER_CN.format((data.available_begin_time?:0)*1000L)}\n")
        timeStringBuilder.append("有效期至：${TimeUtil.yyyy_MM_dd_time_SPOT_FORMATTER_CN.format((data.available_end_time?:0)*1000L)}")
        binding.tvDiscountTime.text = timeStringBuilder.toString()
        binding.tvCampName.text = data.camp_name

        val target = "${H5Url.RECEIVE_COUPON.url}?source=wx_scan_code&camp_id=${couponDetails?.camp_id}&stock_id=${couponDetails?.stock_id}${uidSuffix}"
        var url = "${H5Url.COUPON_SHARE.url}${URLEncoder.encode(target)}"
        getMiniCode(url, onSuccess = {
            binding.ivQrCode.post {
                binding.ivQrCode.setImageBitmap(it)
            }
        })

    }

    private fun getMiniCode(qrCodeUrl:String,
                    onSuccess: ((bitmap: Bitmap) -> Unit)? = {},
                    onFail: ((e: Exception) -> Unit)? = {}){
        if (TextUtils.isEmpty(qrCodeUrl)) {
            return
        }
        Observable.just(qrCodeUrl)
            .observeOn(Schedulers.computation())
            .map { ZXingCodeUtils.createQRCode(it, 300, 300) }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ code ->
                if (BitmapUtil.isBitmapAvailable(code)) {
                    onSuccess?.invoke(code!!)
                } else {
                }
            }, {
            })
    }

    /**
     * 图片加载完成
     */
    override fun checkPictureBitmap(action : ()->Unit){
        val length = imageList.size
        var index = -1
        fun callback(){
            index++
            if(index < length){
                val url = imageList[index]
                ImageUtil.getBitmap(0, url, 0, 0) { _, _ ->
                    callback()
                }
            } else {
                action.invoke()
            }
        }
        callback()
    }

    override fun getMiniProgramPath(): String {
        val target = "${H5Url.RECEIVE_COUPON.url}?source=wx_share&camp_id=${couponDetails?.camp_id}&stock_id=${couponDetails?.stock_id}${uidSuffix}"
        return WXAccount.RECEIVE_PAGA_PATH + URLEncoder.encode(target)
    }

    /**
     * 完整卡片
     */
    override fun getTotalLayoutBitmap() : Bitmap?{
        return ImageUtil.convertViewToBitmap(binding.root,
            GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_375),
            GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_446))
    }

    /**
     * 小程序分享标题
     */
    override fun getTitleForMiniProgram() : String{
        return "营地专属商家券，数量有限，先到先得~"
    }
    /**
     * 小程序分享卡片封面
     */
    override fun getCoverBitmapForMiniProgram(action : (bitmap : Bitmap?)->Unit){
        action.invoke(  BitmapUtil.getBitmap(GlobalContextManager.appContext, R.drawable.bg_wx_coupon_share))
    }
    /**
     * 复制链接 无
     */
    override fun getLinkTxt() : String{
        return ""
    }

    /**
     * 保存到本地
     */
    override fun onSavePicToLocal(source:String,finish:()->Unit){
        checkPictureBitmap {
            savePicToLocal(source,getTotalLayoutBitmap())
            finish()
        }
    }

    private fun savePicToLocal(source:String,bitmap : Bitmap?){
        try {
            if(bitmap != null){
                val path = StorageUtil.getPictureFileWith("camp_share_${way}_${System.currentTimeMillis()}.png")
                var fos: FileOutputStream? = null
                try {
                    fos = FileOutputStream(path)
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
                    fos.flush()
                } catch (e: Exception) {
                } finally {
                    IOUtils.close(fos)
                }
                if (path.exists() && path.length() > 0) {
                    ImageUtil.insertImageToAlbum(context, path.absolutePath)
                    val msg = GlobalContextManager.getString(R.string.share_save_success_toast)
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                } else {
                    val msg = GlobalContextManager.getString(R.string.share_save_fail_toast)
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                }
            }
        } catch (ignore: Exception) {
            val msg = GlobalContextManager.getString(R.string.share_save_fail_toast)
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
        }
    }
}